﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Reflection;
using _18miljard.Mail;

namespace _18miljard
{
	public class Global : System.Web.HttpApplication
	{

		public static MailThread mailThread = null;
		public static bool IsProductionEnvironment = false;
		private static bool isMailBlocked = false;

		protected void Application_Start(object sender, EventArgs e)
		{
			LogWriter.Write("Application started");

			Uri uri = this.Context.Request.Url;
			string absoluteUri = uri.AbsoluteUri;

			string lowerCaseUri = absoluteUri.ToLower();

			//make sure that mails are not sent out if it is not the production environment.
			Global.IsProductionEnvironment = (lowerCaseUri.StartsWith("http://www.18miljard.nl") || lowerCaseUri.StartsWith("http://18miljard.nl"));

			LogWriter.Write("Production environment (" + absoluteUri + "): " + Global.IsProductionEnvironment.ToString(), false);

			Global.MailSignal();
		}

		void Application_End(object sender, EventArgs e)
		{
			ApplicationShutdownReason reason = System.Web.Hosting.HostingEnvironment.ShutdownReason;

			HttpRuntime runtime = (HttpRuntime)typeof(System.Web.HttpRuntime).InvokeMember("_theRuntime", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.GetField, null, null, null);
			string shutDownMessage = (string)runtime.GetType().InvokeMember("_shutDownMessage", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField, null, runtime, null);
			string shutDownStack = (string)runtime.GetType().InvokeMember("_shutDownStack", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField, null, runtime, null);

			LogWriter.Write("Application ended -reason-" + reason.ToString() + " -message-" + shutDownMessage + " -stack-" + shutDownStack);


		}

		void Application_Error(object sender, EventArgs e)
		{
			Exception ex = Server.GetLastError();

			Response.Write("<h2>Global Page Error</h2>\n");
			Response.Write(
				"<p>" + ex.Message + "</p>\n");
			Response.Write("Terug naar <a href='/Default.aspx'>" +
				"Start</a>\n");

			LogWriter.Write(ex);

			Server.ClearError();

		}

		public static void MailSignal()
		{
			if (Global.mailThread != null)
			{
				Global.mailThread.Signal();
			}
			else
				Global.mailThread = new MailThread();
		}

		public static void BlockMail()
		{
			Global.isMailBlocked = true;
		}

		public static void ReleaseMail()
		{
			if (Global.isMailBlocked)
			{
				Global.isMailBlocked = false;

				Global.MailSignal();
			}
		}

		public static bool IsMailBlocked
		{
			get { return Global.isMailBlocked; }
		}

	}
}
